# -*- coding: utf-8 -*-
# 序列化 模型类
import re

from .models import Student,Group,Article,Category,After,Sun,User
from rest_framework import serializers


class StudentSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Student
        fields = ("id","name","age","group")


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ("id","name")

'''
 read_only:True 表示不允许用户自己上传，只能用于api的输出
 write_only
 required 是否必填
 allow_null/ allow_blank 是否允许为NULL /空
'''

class ArticleSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=100,required=True)
    content = serializers.CharField(max_length=1000)
    vum = serializers.IntegerField()

    def create(self, validated_data):
        return Article.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title',instance.title)
        instance.vum = validated_data.get('vum',instance.vum)
        instance.content = validated_data.get('content',instance.content)
        instance.save()
        return instance

'''
ModelSerializer
ModelSerializers默认帮我们实现了创建和更新方法，简化了我们的操作，
当然如果你想自己写，可以重写它。其余使用方法跟普通的序列化一样。
'''


class ArticleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id','title','vum','content')
        # exclude = () 表示不返回
        # fields = '__all__' 表示所有字段



class CategoryModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__' #表示所有字段



# 序列化 StringRelatedField
# StringRelatedField 将返回一个对应关系 model 的 unicode() 方法的字符串。
# 嵌套序列化关系模型
class AfterSerializer(serializers.ModelSerializer):
    sun = serializers.StringRelatedField()

    class Meta:
        model = After
        fields= '__all__'

# depth
# 这个字段可以用来深度遍历
class SunSerializer(serializers.ModelSerializer):
    after = AfterSerializer(many=True)

    class Meta:
        model = Sun
        fields = '__all__'
        depth = 2


# DRF 模型序列化验证
class UserSerializer(serializers.ModelSerializer):
    # 手机号 最多11 最少11 必填
    phone = serializers.CharField(max_length=11,min_length=11,required=True)
    pwd1 = serializers.CharField(write_only=True)

    #gender =serializers.CharField(source='get_gender_display')

    class Meta:
        model = User
        fields = '__all__'

    # 单独验证
    def validate_phone(self,phone):
        if not  re.match(r'1[3456789]\d{9}',phone):
            raise serializers.ValidationError('手机号不合法')

        if User.objects.filter(phone=phone).all():
            raise serializers.ValidationError("手机号已被注册")

        return phone  # 一定要有返回值

    # 多数据验证
    def validate(self, attrs):
        if attrs.get('pwd2') != attrs.get('pwd'):
            raise serializers.ValidationError("两次密码不一样")

        attrs.pop('pwd1')  # 验证后 pop掉
        return attrs



